var fs = require("fs");
var path = require("path");

module.exports = function (UC, source, config, ArFor, cache, package) {
    var UserControl = UC;
    var router = function (req, res, next) {
        var ajaxTest = {
            error: 0
        };
        var Request = req.body;
        if (Request["sourceid"] != null && UserControl.Source(req.session.key, Request["sourceid"])) {

          

            var lastModified = req.getHeader('if-modified-since');
            
            var _etag = req.getHeader('if-none-match');

        

            Request = UserControl.GetForm(req.session.key, Request);
            var _source = new source(Request["sourceid"], Request);

            var start = function (_source) {
                _source.Start(function (db) {
                    

                    var modified = new Date(Date.now());
                    var lastModified = modified.toUTCString();
                    res.lastModified_key=lastModified;
                    // res.setHeader('Cache-Control', "max-age=" + (60 * 60 * 24 * 30));
                    res.Json(db);
                })
            }
            var etag = config.getETag(Object.assign({
                url: config.getdomain(req, req.path)
            }, req.body));
            res.etag_key = etag;
            if (lastModified&&_etag==etag) {
                var modified = new Date(lastModified).getTime();
                if(modified+''=='NaN'){
                    modified=0;
                }
                _source.updateTable(modified, function (off) {
                    if (!off) {
                        req.notModified()
                    } else {
                        start(_source)
                    }
                })
            } else {
                start(_source)
            }
        } else {
            var ajaxTest = {
                error: 1
            };
            res.jsonp(ajaxTest);
        }
    }
    return router;

}